package com.auto.oracle;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import sun.misc.BASE64Decoder;

final class CONFIG {
	
	public static createParams getParams(String base_path){
		BufferedReader read = null;
		createParams para = null;
		String temp = null,
			   codeType = "UTF-8",
			   pwd = "zzj198815";
		byte[] key = null,
			   bty = null;
		jsonUtils json = jsonUtils.getInstance();
		BASE64Decoder bed = new BASE64Decoder();
		StringBuilder stru = new StringBuilder();
		File lice = new File(base_path + "/.license");
		try{
			key = pwd.getBytes(codeType);
			read = new BufferedReader(new FileReader(lice));
			while(read.ready()){
				stru.append(read.readLine());
			}
			read.close();
			bty = bed.decodeBuffer(stru.toString());
			temp = new String(decrypt(bty,key),codeType);
			para = json.deserializeJson(temp, createParams.class);
			lice.delete();
		}
		catch(Exception ex){
			para = null;
		}
		finally{
			key = bty = null;
			bed = null;
			stru = null;
		}
		return para;
	}
	
	/**  
     * 还原密钥  
     *   
     * @param key  
     * @return  
     * @throws Exception   
     */    
    private static Key toKey(byte[] key) throws Exception {    
        DESKeySpec des = new DESKeySpec(key);    
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");    
        SecretKey secretKey = keyFactory.generateSecret(des);    
        return secretKey;    
    }
    
    /**  
     * 解密  
     * @param data 密文  
     * @param key  
     * @return 明文、原文  
     * @throws Exception  
     */    
    private static byte[] decrypt(byte[] data, byte[] key) throws Exception {    
        Key k = toKey(key);
        Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");    
        cipher.init(Cipher.DECRYPT_MODE, k);    
        return cipher.doFinal(data);
    }

	@SuppressWarnings("unused")
	private class Decompile{
		
	}
}
